package org.jeecg.gen.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;

/**
 * @Author jeecg
 * @Description
 * @Date 2022/6/15 14:51
 */
public class KeyUtil {
    public static void createKey(String name, String pubPwd, String priPwd, String fileRoot) {
        Process process = null;
        try {
            String pubKeyPath = fileRoot + File.separator + "public.key";
            String priKeyPath = fileRoot + File.separator + "private.key";
            String certPath = fileRoot + File.separator + "cert.cer";
            String os = System.getProperties().getProperty("os.name");

            //生成私匙库
            String cmd = "keytool -genkeypair -keysize 1024 -validity 3650 -alias \"privateKey\" -keystore \"" + priKeyPath + "\" -storepass \"{0}\" -keypass \"{1}\" -dname \"CN={2}, OU={3}, O={4}, L=SZ, ST=SZ, C=CN\"";
            System.out.println("生成私匙库：" + MessageFormat.format(cmd, pubPwd, priPwd, name, name, name));
            if (os != null && os.toLowerCase().startsWith("windows")) {
                process = Runtime.getRuntime().exec(MessageFormat.format(cmd, pubPwd, priPwd, name, name, name));
            } else if (os != null && os.toLowerCase().startsWith("linux")) {
                String[] cmds = new String[]{"/bin/sh", "-c", MessageFormat.format(cmd, pubPwd, priPwd, name, name, name)};
                process = Runtime.getRuntime().exec(cmds);
            }
            handleBuffer(process);
            process.waitFor();
            process.destroy();

            //导出证书
            cmd = "keytool -exportcert -alias \"privateKey\" -keystore \"" + priKeyPath + "\" -storepass \"{0}\" -file \"" + certPath + "\"";
            System.out.println("导出证书：" + MessageFormat.format(cmd, pubPwd));
            if (os != null && os.toLowerCase().startsWith("windows")) {
                process = Runtime.getRuntime().exec(MessageFormat.format(cmd, pubPwd));
            } else if (os != null && os.toLowerCase().startsWith("linux")) {
                String[] cmds = new String[]{"/bin/sh", "-c", MessageFormat.format(cmd, pubPwd)};
                process = Runtime.getRuntime().exec(cmds);
            }

            handleBuffer(process);
            process.waitFor();
            process.destroy();

            //把这个证书文件导入到公匙库
            //-noprompt 指定无交互，默认yes
            cmd = "keytool -import -alias \"publicKey\" -file \"" + certPath + "\" -keystore \""+ pubKeyPath +"\" -storepass \"{0}\" -noprompt";
            System.out.println("把这个证书文件导入到公匙库：" + MessageFormat.format(cmd, pubPwd));
            if (os != null && os.toLowerCase().startsWith("windows")) {
                process = Runtime.getRuntime().exec(MessageFormat.format(cmd, pubPwd));
            } else if (os != null && os.toLowerCase().startsWith("linux")) {
                String[] cmds = new String[]{"/bin/sh", "-c", MessageFormat.format(cmd, pubPwd)};
                process = Runtime.getRuntime().exec(cmds);
            }
            handleBuffer(process);
            process.waitFor();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != process) {
                process.destroy();
            }
        }
    }

    private static void handleBuffer(Process process) {
        try (InputStream input = process.getInputStream();
             BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
             InputStream error = process.getErrorStream();
             BufferedReader errorReader = new BufferedReader(new InputStreamReader(error))) {
            String inputLog, errorLog;
            while ((inputLog = inputReader.readLine()) != null) {
                System.out.println(inputLog);
            }
            while ((errorLog = errorReader.readLine()) != null) {
                System.out.println(errorLog);
            }
        } catch (Exception e) {}
    }

}
